/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["register", function (require, exports, module) {
    function diffEmail(email) {
        return /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(email);
    };

    const verify = require("verify");

    let verified = false;
    let verifing = false;

    $('#verify').click(function () {
        if (verified || verifing) return;
        verifing = true;
        this.disabled = true;
        verify.start().then(id => {
            verifing = false;
            this.disabled = false;
            if (id) {
                verified = true;
                this.disabled = true;
            }
        })
    });

    $('#registerButton').click(function () {
        var email = $('#email').val();
        var password = $('#password').val();
        var url = '/api/register';
        var name = $('#name').val();
        var img = $('#img').val();
        var code = $('#code').val();

        this.disabled = true;
        $.post(url, {
            email: email,
            pw: password,
            code: code,
            img: img,
            name: name
        }).done((data) => {
            data = JSON.parse(data)
            if (data.code == 200) {
                swal.skip({
                    title: "注册成功"
                });
            } else {
                swal("注册失败", data.msg, "error");
                this.disabled = false;
            }
        }).fail((error) => {
            swal("注册失败", error, "error");
            this.disabled = false;
        });
    });

    $('#send_code').click(function () {
        var email = $('#email').val();
        if (!email || !diffEmail(email)) {
            return swal("发送失败", "请先正确填写邮箱~", "warning");
        };

        this.disabled = true;
        $.post("/api/code/send", {
            email: email
        }).done((data) => {
            if (data.code == 403) {
                swal("发送失败", "请勿操之过急哦~", "warning");
                this.disabled = false;
            } else {
                swal("发送成功", "咻~验证码已发送！", "success");
                var c = 60;
                this.innerText = String(c);
                var x = setInterval(() => {
                    c--;
                    this.innerText = String(c);
                    this.disabled = true;
                    if (c <= 0) {
                        this.innerText = "发送";
                        this.disabled = false;
                        clearInterval(x);
                    }
                }, 1000);
            }
        }).fail((error) => {
            swal("发送失败", error, "warning");
            this.disabled = false;
        });
    });
}]);